package cn.dxh.stagefinal.controller;

import cn.dxh.stagefinal.bean.*;
import cn.dxh.stagefinal.config.PageConfig;
import cn.dxh.stagefinal.service.DepartmentService;
import cn.dxh.stagefinal.service.EmployeeService;
import cn.dxh.stagefinal.service.RoleService;
import cn.dxh.stagefinal.utils.EmployeeExcelUtils;
import cn.dxh.stagefinal.utils.ProviderExcelUtils;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;


import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.PrintWriter;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * IntelliJ IDEA -> stagefinal
 * 2019/12/10 10:17
 *
 * @author zmyao
 * 别看，我是渣渣。
 */
@Controller
public class EmployeeController {
    @Autowired
    private EmployeeService employeeService;
    @Autowired
    private DepartmentService departmentService;
    @Autowired
    private RoleService roleService;

    @RequestMapping("/record/selectemployee")
    public String selectemployee(@RequestParam(defaultValue = "1") Integer index, String eName, @RequestParam(defaultValue = "0") Integer dId, ModelMap map, HttpServletRequest  request) {
        if (index == 0) {
            index = 1;
        }
        HttpSession session = request.getSession();
        Employee currentUser = (Employee) session.getAttribute("currentUser");
        Integer  rLevel = currentUser.getRole().getrLevel();
        PageInfo<Employee> emppage = employeeService.findEmployees(index, PageConfig.PAGE_SIZE, eName, dId,rLevel);
//        System.out.println(rLevel+"****"+emppage.getList().size());
        List<Department> departments = findDepartments();
        map.addAttribute("departments", departments);
        map.addAttribute("index", index);
        map.addAttribute("emppage", emppage);
        map.addAttribute("eName", eName);
        map.addAttribute("dId", dId);
        return "/record/employeelist";
    }

    //查询所有的部门列表
    public List<Department> findDepartments() {
        return departmentService.findDepartments();
    }

    //查询所有职位的列表
    public List<Role> findRoles() {
        return roleService.findRoles();
    }

    public List<String> findSexs() {
        ArrayList<String> sexs = new ArrayList<>();
        sexs.add("女");
        sexs.add("男");
        return sexs;
    }

    @RequestMapping("/record/insertemployee.html")
    public String insertEmp(ModelMap map) {
        map.addAttribute("departments", findDepartments());
        map.addAttribute("roles", findRoles());
        return "/record/insertemployee";
    }

    @RequestMapping("/record/insertemployee")
    public void insertempartment(Employee employee, HttpServletResponse response) {
        try {
            int len = employeeService.insertEmployee(employee);
            response.setContentType("text/html;charset= utf-8");
            PrintWriter out = response.getWriter();
            if (len > 0) {
                out.println("<script> alert('员工添加成功');location.href='/record/selectemployee'</script>");
            } else if (len == -1) {
                out.println("<script> alert('请选择部门或者职位');location.href='/record/insertemployee.html';</script>");
            }  else if (len == -2) {
                out.println("<script> alert('这个登录名有人使用了');location.href='/record/insertemployee.html';</script>");
            } else {
                out.println("<script> alert('员工添加失败');location.href='/record/insertemployee.html';</script>");
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    //修改密码的页面
    @RequestMapping("/record/updateemployeepwd.html")
    public String updatePwd(Integer eId, ModelMap map) {
        map.addAttribute("eId", eId);
        return "/record/updateemployeepwd";
    }

    //*修改密码
    @RequestMapping("/record/updateemppwd")
    public void updateemployeepwd(Integer eId, String newPassword, String rePassword, HttpServletResponse response) {
        try {
            int len = employeeService.updateemployeepwd(eId, newPassword, rePassword);
            response.setContentType("text/html;charset= utf-8");
            PrintWriter out = response.getWriter();
            if (len > 0) {
                out.write("<script> alert('密码修改成功');location.href='/record/selectemployee'</script>");
            } else if (len == -1) {
                out.write("<script> alert('两次密码输入不正确');location.href='/record/updateemployeepwd.html?eId=" + eId + "';</script>");
            } else if (len == -2) {
                out.write("<script> alert(' 请输入密码');location.href='/record/updateemployeepwd.html?eId=" + eId + "';</script>");
            } else {
                out.write("<script> alert('密码修改失败');location.href='/record/updateemployeepwd.html?eId=" + eId + "';</script>");
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    ///修改员工的信息页面
    @RequestMapping("/record/updateemployee.html")
    public String updateemp(Integer eId, ModelMap map) {
        Employee employee = employeeService.findEmployeeByeId(eId);
        map.addAttribute("employee", employee);
        map.addAttribute("departments", findDepartments());
        map.addAttribute("roles", findRoles());
        map.addAttribute("sexs", findSexs());
        return "/record/updateemployee";
    }

    //*修改员工的信息
    @RequestMapping("/record/updateemployee")
    public void updateemployee(Employee employee, HttpServletResponse response) {
        try {
            int len = employeeService.updateemployee(employee);
            Integer eId = employee.getdId();
            response.setContentType("text/html;charset= utf-8");
            PrintWriter out = response.getWriter();
            if (len > 0) {
                out.write("<script> alert('员工信息修改成功');location.href='/record/selectemployee'</script>");
            } else {
                out.write("<script> alert('员工信息修改失败');location.href='/record/updateemployee.html?eId=" + eId + "';</script>");
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @RequestMapping("/record/deletemployee.html")
    public void deleteEmployee(Integer eId, HttpServletResponse response) {
        try {
            int len = employeeService.deleteEmployeeByEid(eId, 0);
            response.setContentType("text/html;charset= utf-8");

            PrintWriter out = response.getWriter();
            if (len > 0) {
                out.write("<script> alert('删除成功');location.href='/record/selectemployee'</script>");
            } else {
                out.write("<script> alert('删除失败');location.href='/record/selectemployee';</script>");
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }


    @RequestMapping("/record/deleteanddaochuemployee")
    public void deleteanddaochuemployee(String method, int[] eIds, HttpServletResponse response) {
        try {
            response.setContentType("text/html;charset=utf-8");
            PrintWriter out = response.getWriter();
            if ("delete".equals(method)) {
                int len = employeeService.updateEmployeeEstateByEids(eIds, 0);
                if (len > 0) {
                    out.println("<script> alert('全部删除成功');location.href='/record/selectemployee';</script>");
                }
                out.println("<script> alert('删除失败');location.href='/record/selectemployee';</script>");
            } else if ("daochu".equals(method)) {
                List<Employee> employeeList = employeeService.findEmployeesByEids(eIds);
                EmployeeExcelUtils.createFirst("人员信息");
                EmployeeExcelUtils.createOthers(employeeList);
                SimpleDateFormat format = new SimpleDateFormat("yyyyMMddHHmmss");
                EmployeeExcelUtils.export(new FileOutputStream("d:\\javaCreate\\" + "employee" + (format.format(new Date())) + ".xls"));
                out.println("<script> alert('导出成功');location.href='/record/selectemployee';</script>");
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @RequestMapping("/record/checkLoginName")
    @ResponseBody
    public Massage  checkLoginName(String loginName) {
        Employee employee = employeeService.findEmployeeByLoginName(loginName);
        Massage massage = new Massage();
        if (employee == null ){
            massage.setMassage(loginName+"可用");
        }
        else {
            massage.setMassage(loginName+"已经存在");
        }
        return   massage;
    }
}
